<template>
  <div class="app-container">
    <div class="collect-template">
      <el-form v-column="3" :model="dataFilter">

        <el-form-item label="组织">
          <org-tree-select 
            v-model="dataFilter.orgId" 
            @change="getList"
          />
        </el-form-item>

        <el-form-item label="模板名称">
          <el-input v-model="dataFilter.templateName" placeholder="请输入"/>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="onSearch">查询</el-button>
          <el-button @click="onReset">重置</el-button>
        </el-form-item>
      </el-form>

      <div style="margin-bottom: 20px;">
        <el-button type="primary" @click="handleAdd">添加</el-button>
        <el-button type="danger" :disabled="!multipleSelection.length" @click="handleDelete">删除</el-button>
      </div>
      <el-table
        :data="sourceData.list"
        border
        highlight-current-row
        stripe
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="40" />
        <el-table-column label="模板名称" prop="templateName" />
        <el-table-column label="所属组织" prop="orgName" />
        <el-table-column label="变量数量" prop="changeNum">
          <template #="{ row }">
            <router-link :to="`/equipmentVar?id=${row.id}`" style="color: #03CCA1;">
              {{ row.changeNum }}
            </router-link>
          </template>
        </el-table-column>
        <el-table-column label="关联设备数" prop="equipNum" />
        <el-table-column label="采集协议" prop="protocolName" />
        <el-table-column label="操作" align="center" width="180">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleAddVar(row)">
              添加变量
            </el-button>
            <el-button type="primary" link @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button type="danger" link @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <Pagination :pageProps="pageProps" layout="prev, pager, next" @current-change="getList" />
    </div>
  </div>

  <EquipmentTemplateDialog ref="dialog" @listChange="itemData" />
  <EquipmentTemplateAddDialog ref="dialogVar" @listChange="itemData" />
  <EquipmentVarDialog ref="drawVar" @refresh="getList" />
</template>

<script setup lang="ts">
import { reactive, ref, nextTick, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { templateList, templateDetail, dellTemplate } from '@/api/collect'
import Pagination from '@/components/Pagination/Index.vue'
import EquipmentTemplateDialog from './components/EquipmentTemplateDialog.vue'
import EquipmentTemplateAddDialog from './components/EquipmentTemplateAddDialog.vue'
import EquipmentVarDialog from './components/EquipmentVarDialog.vue'
import OrgTreeSelect from '@/components/OrgTreeSelect/index.vue'

const dataFilter = reactive({
  orgId: null,
  templateName: undefined,
})

const pageProps = ref({
  pageNum: 1,
  pageSize: 10,
  total: 0,
})

const sourceData = reactive({
  list: [] as any,
})

const getList = () => {
  templateList({
    pageNum: pageProps.value.pageNum,
    pageSize: pageProps.value.pageSize,
    ...dataFilter
  }).then((res)=>{
    console.log('res', res)
    sourceData.list = res.data.records
    // TODO use real api total res total
    pageProps.value.total = res.data.total
  })
  .catch((err) => {
    console.error('err', err)
  })
}

getList()

// const onOrgIdChange = (v: any) => {
//   dataFilter.orgId = v
//   getList()
// }

const onSearch = () => {
  getList()
}

const onReset = () => {
  // TODO use method component
  dataFilter.orgId = null
  dataFilter.templateName = undefined
  Object.assign(pageProps.value, {
    pageNum: 1,
    pageSize: 10,
    total: 0,
  })
}

const dialog: any = ref(null)

const handleAdd = () => {
  // dialog.value.reset()
  // console.log('tableItem', dialog.value.tableItem)
  dialog.value.dialogVisible = true
  dialog.value.isDisabled = true
  dialog.value.dialogStatus = 'create'
}

const dialogVar: any = ref(null)

const drawVar = ref<InstanceType<typeof EquipmentVarDialog>>()
const handleAddVar = (row) => {
  // dialog.value.reset()
  // console.log('tableItem', dialog.value.tableItem)
  drawVar.value?.init({ templateId: row.id })
}

const handleEdit = (row: any) => {
  dialog.value.dialogVisible = true
  dialog.value.dialogStatus = 'edit'
  nextTick(()=>{
    templateDetail(row.id)
    .then((res)=>{
      console.log('res', res)
      Object.assign(dialog.value.tableItem, res.data)
    })
    .catch((err)=>{
      console.error('err', err)
    })
  })
}

const itemData = () => {
  getList()
}

const multipleSelection = ref<any>([])

const handleSelectionChange = (val: any[]) => {
  multipleSelection.value = val.map(item=>item.id);
}

const handleDelete = (row: any) => {
  ElMessageBox.confirm(
    '确定要删除吗?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
  .then(() => {  
    const params = {
      idList: multipleSelection.value
    }
    if (row.id) params.idList = [row.id]
    dellTemplate(params)
    .then((res: any) => {
      ElMessage.success('删除成功！')
      getList()
    })
    .catch((err: any) => {
      console.error('err', err.msg)
      ElMessage.success('删除失败！')
      getList()
    })
  })
  .catch(() => {})
}
</script>

<style scoped>
.app-container {
  flex: 1;
}
</style>